<template>
  <page-header-wrapper>
    <page-tab-list>
      <div class="table-page-search-box">
        <a-form layout="inline">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="小程序">
                <a-select placeholder="请选择" v-model="queryParam.id" @change="getList()">
                  <a-select-option :value="item.id" v-for="item of idList" :key="item.id">
                    {{ item.app_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :span="6">
              <a-form-item label="发放时间">
                <a-range-picker
                  allowClear
                  format="YYYY-MM-DD"
                  valueFormat="YYYY-MM-DD"
                  :placeholder="['开始时间', '结束时间']"
                  v-model="queryTime"
                  @change="changeTime"
                />
                <!-- @calendarChange="calendarChange" -->
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="">
                <a-button type="primary" @click="getList()">查询</a-button>
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </page-tab-list>

    <a-card :border="false">
      <div class="table-operator" style="display: flex; justify-content: space-between">
        <div>
          <a-radio-group v-model="queryParam.status" @change="getList()">
            <a-radio-button value=""> 全部 </a-radio-button>
            <a-radio-button value="1"> 已激活 </a-radio-button>
            <a-radio-button value="2"> 已停止 </a-radio-button>
            <a-radio-button value="0"> 未激活 </a-radio-button>
          </a-radio-group>
        </div>

        <a-button type="primary" @click="$router.push({ name: 'voucherAdd' })" icon="plus">新建</a-button>
      </div>

      <a-table
        size="default"
        :columns="columns"
        :data-source="list"
        :row-key="record => record.id"
        :pagination="{
          total: this.total,
          pageSize: this.pageSize,
          showSizeChanger: false,
          onChange: this.tablePageChange
        }"
      >
        <span slot="time" slot-scope="text, record">
          {{ record.publish_start_time }}至{{ record.publish_end_time }}
        </span>

        <span slot="name" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">
              {{ text.name }}
            </template>
            <div class="name">
              {{ text.name }}
            </div>
          </a-tooltip>

          <a-tooltip>
            <template slot="title">
              {{ getLimit(text) }}
            </template>
            <div class="name">
              {{ getLimit(text) }}
            </div>
          </a-tooltip>
        </span>

        <span slot="info" slot-scope="text, record">
          <div class="flex">
            <div class="img">
              <a-avatar :size="48" :src="record.voucher_display_pattern_info.brand_logo_url" />
            </div>
            <div class="txt">
              <div class="s1">{{record.voucher_display_pattern_info.brand_name}}</div>
              <div class="s2">{{record.voucher_display_pattern_info.customer_service_mobile}}</div>
            </div>
          </div>
        </span>

        <span slot="voucher_type" slot-scope="text, record">
          {{ text.discount_type === 1 ? '折扣' : '满减' }}
        </span>

        <span slot="preferential_amount" slot-scope="text, record">
          {{ getPreferentialAmount(text) }}
        </span>

        <span slot="discount" slot-scope="text, record">
          {{ getDiscount(text) }}
        </span>

        <span slot="created_at" slot-scope="text, record">
          <template v-if="record.expire_type === 1">
            领取后{{record.voucher_use_rule_info.voucher_use_time_info.relative_period_info.wait_days_after_receive}}
            天生效
            <div>
              生效后{{record.voucher_use_rule_info.voucher_use_time_info.relative_period_info.valid_days_after_receive}}天内有效
            </div>
          </template>
          <template v-else>
            有效期范围
            <div>
              {{record.begin_time | timeFormat}}
            </div>
            -
            <div>
              {{record.end_time | timeFormat}}
            </div>
          </template>
        </span>

        <span slot="activity_status" slot-scope="text, record">
          <a-badge :color="getStatus(text.activity_base_info.activity_status)[1]" :text="getStatus(record.activity_base_info.activity_status)[0]" />
        </span>

        <span slot="action" slot-scope="text, record">
          <a @click="handle('remove', text)">删除</a>

          <template v-if="text.activity_base_info.activity_status !== 'FINISHED'">
            <a-divider type="vertical" />
            <a-dropdown>
              <a class="ant-dropdown-link"> 更多 <a-icon type="down" /> </a>
              <a-menu slot="overlay">
                <a-menu-item>
                  <a 
                    href="javascript:;" 
                    @click="
                      $router.push({ 
                        path: `/marketing/alipayPromotion/voucherEdit?id=${record.alipay_activity_id}&min_id=${record.mini_id}`  
                      })">
                    编辑
                  </a>
                </a-menu-item>
                  <a-menu-item v-if="text.activity_base_info.activity_status === 'ACTIVE'">
                    <a href="javascript:;" @click="handle('stop', text)">停止</a>
                  </a-menu-item>
                  <a-menu-item v-if="text.activity_base_info.activity_status === 'INIT'">
                    <a href="javascript:;" @click="handle('activate', text)">激活</a>
                  </a-menu-item>
                  <a-menu-item v-if="text.activity_base_info.activity_status === 'ACTIVE'">
                    <a href="javascript:;" @click="handle('add', text)">追加券数量</a>
                  </a-menu-item>
              </a-menu>
            </a-dropdown>
          </template>

        </span>
      </a-table>
    </a-card>

    <!-- 新增编辑 -->
    <a-modal
      title="增加券"
      :width="500"
      :confirm-loading="modalLoading"
      :mask-closable="false"
      v-model="visible"
      @ok="handleOk"
    >
      <el-form
        :rules="modifyRules"
        label-width="120px"
        :model="modifyForm"
        label-suffix="："
        ref="modifyForm"
        size="small"
      >
        <el-form-item label="追加到数量" prop="voucher_quantity">
          <a-input-number placeholder="请输入" :min="min"  v-model="modifyForm.voucher_quantity" />
        </el-form-item>

        <template slot="footer">
          <a-button v-loading="modalLoading" type="primary" @click="handleOk"> 提交 </a-button>
          <a-button style="margin-left: 10px" @click="visible = false"> 取消 </a-button>
        </template>
      </el-form>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import {
  voucherList,
  voucherAppend,
  voucherPublish,
  voucherStop,
  voucherRemove
} from '@/api/marketing/alipayPromotion'
import { alipayList } from '@/api/setting/applet'

const columns = [
  {
    title: 'ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '优惠券名称',
    scopedSlots: {
      customRender: 'name'
    },
    width: 120
  },
  {
    title: '商户信息',
    scopedSlots: {
      customRender: 'info'
    },
    width: 200
  },
  {
    title: '最低消费',
    dataIndex:'min_price'
  },
  {
    title: '领取数量',
    dataIndex:'voucher_inventory_info.send_count'
  },
  {
    title: '使用数量',
    dataIndex:'voucher_inventory_info.use_count'
  },
  {
    title: '优惠方式',
    scopedSlots: {
      customRender: 'voucher_type'
    }
  },
  {
    title: '优惠金额',
    scopedSlots: {
      customRender: 'preferential_amount'
    }
  },
  {
    title: '折扣',
    scopedSlots: {
      customRender: 'discount'
    }
  },
  // {
  //   title: '发放数量',
  //   dataIndex: 'quantity',
  //   sorter: (a, b) => parseInt(a.quantity) - parseInt(b.quantity)
  // },
  // {
  //   title: '最大优惠金额',
  //   dataIndex: 'ceiling_amount',
  //   sorter: (a, b) => parseInt(a.ceiling_amount) - parseInt(b.ceiling_amount)
  // },
  {
    title: '券数量',
    dataIndex: 'voucher_send_mode_info.voucher_send_rule_info.quantity',
    sorter: (a, b) => parseInt(a.voucher_send_mode_info.voucher_send_rule_info.quantity) - parseInt(b.voucher_send_mode_info.voucher_send_rule_info.quantity)
  },
  {
    title: '状态',
    scopedSlots: {
      customRender: 'activity_status'
    },
    width: 120,
    sorter: (a, b) => a.activity_status - b.activity_status
  },
  {
    title: '发放时间',
    scopedSlots: {
      customRender: 'time'
    },
    width: 200
  },
  {
    title: '有效时间',
    scopedSlots: {
      customRender: 'created_at'
    },
    width: 120
  },
  {
    title: '操作',
    scopedSlots: {
      customRender: 'action'
    },
    width: 150
  }
]

export default {
  data() {
    return {
      queryTime: [],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      columns,
      idList: [],
      serviceList: [],
      queryParam: {
        publish_start_time: '',
        publish_end_time: '',
        id: '',
        status: ''
      },

      list: [],
      startTime: '',

      modifyForm: {
        voucher_quantity: 1
      },
      modifyRules: {
        voucher_quantity: [{ required: true, message: '请输入追加数量', trigger: 'blur' }]
      },
      modalLoading: false,
      visible: false,
      min:0
    }
  },

  watch: {
    visible(_val) {
      if (_val) {
        this.$refs.modifyForm.resetFields()
      }
    }
  },

  computed: {
    getLimit(){
      return (item)=>{
        let {voucher_send_rule_info} = item.voucher_send_mode_info,
          {quantity_limit_per_user,quantity_limit_per_user_period_type} = voucher_send_rule_info,
          str = '';

        switch(quantity_limit_per_user_period_type){
          case 'LIFE_CYCLE':
            str = '整个活动周期'
            break
          
          case 'DAY':
            str = '每天'
            break

          case 'MONTH':
            str = '每月'
            break

          case 'WEEK':
            str = '每周'
            break
        }

        str+=`领取${quantity_limit_per_user}张`

        return !quantity_limit_per_user_period_type ? '无限制领取' : str
      }
    },

    getStatus() {
      return status => {
        let text, color
        switch (status) {
          case 'ACTIVE':
            text = '进行中'
            color = 'rgb(101, 200, 23)'
            break

          case 'PAUSE':
            text = '已暂停'
            color = '#FF4D4F'
            break

          case "FINISHED":
            text = '已停止'
            color = '#FF4D4F'
            break

          case 'INIT':
            text = '未激活'
            color = '#FF4D4F'
            break
        }
        return [text, color]
      }
    },

    getPreferentialAmount() {
      return item => {
        if (item.discount_type === 2) {
          return item.sub_price || '0.00'
        }

        return '0.00元'
      }
    },

    getDiscount() {
      return item => {
        if (item.discount_type === 1) return '10.0折'

        return item.discount + '折'
      }
    }
  },

  mounted() {
    const hide = this.$message.loading('加载中', 0)

    alipayList()
      .then(res => {
        hide()
        if (!res.code && res.data && res.data.length) {
          this.idList = res.data
          this.queryParam.id = res.data[0].id
          this.getList()
        }
      })
      .catch(err => {
        hide()
      })
  },

  methods: {
    handle(type, { alipay_activity_id,mini_id,voucher_send_mode_info }) {
      const hide = this.$message.loading('加载中', 0)

      switch (type) {
        case 'remove':
          voucherRemove({
            alipay_activity_id,
            id: mini_id
          })
            .then(res => {
              hide()
              if (!res.code) {
                this.$message.success('操作成功~')
                this.getList()
                return
              }
              this.$message.error(res.msg)
            })
            .catch(() => {
              hide()
            })
          break

        case 'stop':
          voucherStop({ alipay_activity_id, id: mini_id })
            .then(res => {
              hide()

              if (!res.code) {
                this.$message.success('操作成功~')
                this.getList()
                return
              }
              this.$message.error(res.msg)
            })
            .catch(() => {
              hide()
            })
          break
          
        case 'activate':
            voucherPublish({ alipay_activity_id, id: mini_id })
            .then(res => {
              hide()

              if (!res.code) {
                this.$message.success('操作成功~')
                this.getList()
                return
              }
              this.$message.error(res.msg)
            })
            .catch(() => {
              hide()
            })
          break;

        case 'add':
          hide()
          
          this.min = parseInt(voucher_send_mode_info.voucher_send_rule_info.quantity);
          this.modifyForm = {
            voucher_quantity:parseInt(voucher_send_mode_info.voucher_send_rule_info.quantity),
            alipay_activity_id,
            id: mini_id
          }
          this.visible = true
          break
      }
    },

    handleOk() {
      this.$refs.modifyForm.validate(async valid => {
        if (valid) {
          this.modalLoading = true

          const res = await voucherAppend(this.modifyForm)
          this.modalLoading = false
          if (!res.code) {
            this.$message.success(res.msg)
            this.visible = false
            this.getList()
            return
          }

          this.$message.error(res.msg)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },

    // 切换筛选时间
    changeTime(e) {
      if (e.length) {
        this.queryParam.publish_start_time = e[0]
        this.queryParam.publish_end_time = e[1]
      } else {
        this.queryParam.publish_start_time = ''
        this.queryParam.publish_end_time = ''
      }
    },

    // 获取数据列表
    async getList(page = 1) {
      const hide = this.$message.loading('加载中', 0)
      let { queryParam, pageSize } = this

      const res = await voucherList({
        ...queryParam,
        pageSize: String(pageSize),
        page: String(page)
      })

      if (res.code == 0) {
        let { count: total, data: list } = res
        this.total = total
        this.list = list || []
      }
      hide()
    },

    // 分页请求
    tablePageChange(e) {
      this.getList(e)
    },

    // 点击单个
    handleItem(type, { id }) {
      switch (type) {
        case 'stop':
          voucherStop(id).then(res => {
            if (!res.code) {
              this.$message.success(res.msg)
              this.getList()
              return
            }

            this.$message.error(res.msg)
          })
          break
      }
    }
  }
}
</script>

<style lang="less" scoped>
.name {
  width: 160px;
}

.flex{
  display: flex;
  align-items: center;

  .txt{
    margin-left: 10px;
    flex:1;

    div{
      font-size:14px;
    }

    .s1{
      color:#333;
      font-weight: bold;
    }

    .s2{
      color:#999;
    }
  }
}
</style>
